package org.hackystat.devcathlon.ui.page.matches;

import java.util.Iterator;
import java.util.List;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.OrderByBorder;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.Model;
import org.hackystat.devcathlon.engine.match.MatchManager;
import org.hackystat.devcathlon.engine.team.Team;
import org.hackystat.devcathlon.ui.DevcathlonSession;
import org.hackystat.devcathlon.ui.page.teams.profile.TeamsProfile;
import org.hackystat.utilities.tstamp.Tstamp;

/**
 * The Matches element for the Match's main page.
 * 
 * @author John Zhou
 * 
 */
public class MatchesPanel extends Panel {
  /** Support serialization. */
  private static final long serialVersionUID = 1L;

  /**
   * Initialize.
   * 
   * @param wicketId A Wicket identifier from the html tag.
   * @param listItem A list of matches.
   */
  public MatchesPanel(String wicketId, List<String> listItem) {
    super(wicketId);

    // Check if there are any matches, if no set the label.
    String noMatches = "";

    if (listItem.isEmpty()) {
      noMatches = "There are no matches";
    }
    add(new Label("noMatches", noMatches));
    SortableMatchProvider matchInfo = new SortableMatchProvider(listItem);
    final DataView matchView = new DataView("ItemList", matchInfo) {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      @Override
      protected void populateItem(Item item) {
        final String matchName = (String) item.getModelObject();
        item.add(new Label("MatchLabel", matchName));
        item.add(new Link("MatchDetailsLink") {
          public boolean isVisible() {
            return DevcathlonSession.get().getEmail() != null;
          }
          /** Support serialization. */
          private static final long serialVersionUID = 1L;

          /** Upon clicking this link, go to Match page */
          @Override
          public void onClick() {
            try {
              setResponsePage(new MatchDetailPage(matchName));
            }
            catch (Exception e) {
              // if there is an exception error
              e.printStackTrace();
            }
          }
        });
        String status = "";
        try {
          if (Tstamp.lessThan(Tstamp.makeTimestamp(), MatchManager.getInstance()
              .getMatch(matchName).getEndTime())) {
            status = "ends " + MatchManager.getInstance().getMatch(matchName).printEndDateTime();
          }
          else {
            status = "Completed";
          }
        }
        catch (Exception e) {
          // if there is an Tstamp error
          e.printStackTrace();
        }
        item.add(new Label("StatusLabel", status));

        WebMarkupContainer row1 = new WebMarkupContainer("Team1Row");
        WebMarkupContainer row2 = new WebMarkupContainer("Team2Row");

        Iterator<Team> iTeam = MatchManager.getInstance().getMatch(matchName).getTeams().iterator();
        final Team team1 = iTeam.next();
        row1.add(new Link("Team1Link") {
          /** Support serialization. */
          private static final long serialVersionUID = 1L;

          /** Upon clicking this link, go to Team page. */
          @Override
          public void onClick() {
            DevcathlonSession.get().getTeamsSession().setSelectedTeam(team1.getName());
            setResponsePage(new TeamsProfile());
          }
        }
        .add(new Label("Team1Label", team1.getName())));
        Integer team1Points = MatchManager.getInstance().getMatch(matchName).getTeamPoints(team1);
        row1.add(new Label("Team1PointsLabel", team1Points.toString()));
        final Team team2 = iTeam.next();
        row2.add(new Link("Team2Link") {
          /** Support serialization. */
          private static final long serialVersionUID = 1L;

          /** Upon clicking this link, go to Team page. */
          @Override
          public void onClick() {
            DevcathlonSession.get().getTeamsSession().setSelectedTeam(team2.getName());
            setResponsePage(new TeamsProfile());
          }
        }
        .add(new Label("Team2Label", team2.getName())));
        Integer team2Points = MatchManager.getInstance().getMatch(matchName).getTeamPoints(team2);
        row2.add(new Label("Team2PointsLabel", team2Points.toString()));

        if (status.compareTo("Completed") == 0) {
          if (team1Points > team2Points) {
            row1.add(new AttributeModifier("bgcolor", new Model("#6B90DB")));
          }
          else if (team1Points < team2Points) {
            row2.add(new AttributeModifier("bgcolor", new Model("#6B90DB")));
          }
        }

        item.add(row1);
        item.add(row2);
      }
    };
    matchView.setItemsPerPage(5);
    add(new OrderByBorder("OrderByNames", "name", matchInfo) {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      protected void onSortChanged() {
        matchView.setCurrentPage(0);
      }
    });
    add(new OrderByBorder("OrderByDates", "date", matchInfo) {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      protected void onSortChanged() {
        matchView.setCurrentPage(0);
      }
    });
    add(matchView);
    add(new PagingNavigator("MatchNavigator", matchView));
  }
}
